package com.budwk.app.sqfwV2.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfwV2.dto.entity.AssistanceFormSummaryDraft;
import com.budwk.app.sqfwV2.service.AssistanceSummaryDraftService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.IpUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.log.model.Sys_log;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@IocBean(args = {"refer:dao"})
public class AssistanceSummaryDraftServiceImpl extends BaseServiceImpl<AssistanceFormSummaryDraft> implements AssistanceSummaryDraftService {
    public AssistanceSummaryDraftServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SysUserService userService;
    @Inject
    private SysLogService sysLogService;
    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;


    @Override
    public void submitData(AssistanceFormSummaryDraft draft) {
        Sys_user user = userService.fetch(SecurityUtil.getUserId());
        String id = draft.getId();
        if (StringUtils.isNotEmpty(id)) {
            draft.setUpdateBy(SecurityUtil.getUserId()).setUpdateDate(LocalDateTime.now());
            this.updateIgnoreNull(draft);
            return;
        }
        draft.setUnitId(SecurityUtil.getUnitId())
                .setProvince(user.getProvince())
                .setCity(user.getCity())
                .setDistrict(user.getDistrict())
                .setCounty(user.getCounty())
                .setCommunity(user.getCommunity())
                .setCreateBy(user.getId())
                .setCreateDate(LocalDateTime.now())
                .setUpdateBy(user.getId())
                .setUpdateDate(LocalDateTime.now());
        this.insert(draft);
    }

    @SLog(tag = "删除草稿箱功能", value = "${args[0]}")
    @Override
    public void deleteData(String draftId) {
        log.info("AssistanceSummaryDraftServiceImpl deleteData draftId : {}", draftId);
        if (StringUtils.isEmpty(draftId)) {
            return;
        }
        // 删除数据
        this.delete(draftId);
    }

    @Override
    public List<AssistanceFormSummaryDraft> queryAll(AssistanceFormSummaryDraft dto) {
        if (StringUtils.isEmpty(dto.getType())) {
            return Lists.newArrayList();
        }
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        where.andEquals(AssistanceFormSummaryDraft::getUnitId, SecurityUtil.getUnitId())
                .andEquals(AssistanceFormSummaryDraft::getType, dto.getType());
        // 按照更新时间降序
        cnd.getOrderBy().desc(AssistanceFormSummaryDraft::getUpdateDate);
        List<AssistanceFormSummaryDraft> list = this.query(cnd);
        if (list.size() == 0) {
            return list;
        }
        // 异步处理数据
        Set<String> updateIds = list.stream().map(AssistanceFormSummaryDraft::getUpdateBy).collect(Collectors.toSet());
        List<Sys_user> users = userService.getUserByIds(updateIds);
        for (AssistanceFormSummaryDraft assistanceFormSummaryDraft : list) {
            Optional<Sys_user> optional = users.stream().filter(e -> e.getId().equals(assistanceFormSummaryDraft.getUpdateBy())).findFirst();
            optional.ifPresent(sysUser -> assistanceFormSummaryDraft.setUpdateName(sysUser.getUsername()));
        }
        return list;
    }
}
